package com.turato.json.gson.demo;

import com.google.gson.reflect.TypeToken;
import com.turato.json.model.bo.StudentBO;
import com.turato.json.gson.GsonUtil;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author tuhao
 * @date 2020/11/25 11:44 上午
 * @desc
 */
public class GsonDemo {
    StudentBO studentA = new StudentBO();
    StudentBO studentB = new StudentBO();
    StudentBO studentC = new StudentBO();
    StudentBO studentD = new StudentBO();
    private List<StudentBO> studentBOList = new ArrayList();

    @Before
    public void initTest() {
        studentA.setId(1);
        studentA.setAge(20);
        studentA.setName("Tom");
        studentA.setClassId(1);
        studentA.setScore(100);
        studentA.setHeight(175);
        studentA.setWeight(60);

        studentB.setId(2);
        studentB.setAge(19);
        studentB.setName("Ken");
        studentB.setClassId(2);
        studentB.setScore(60);
        studentB.setHeight(180);
        studentB.setWeight(60);

        studentC.setId(3);
        studentC.setAge(19);
        studentC.setName("Bob");
        studentC.setClassId(2);
        studentC.setScore(70);
        studentC.setHeight(175);
        studentC.setWeight(80);

        studentBOList.add(studentA);
        studentBOList.add(studentB);
        studentBOList.add(studentC);
        studentBOList.add(studentD);
    }

    /**
     * JsonElement.java
     */

    @Test
    public void gsonTest() {
        //对象1
        String integerString = GsonUtil.toJson(1);
        Integer one = GsonUtil.fromJson(integerString, Integer.class);
        System.out.println(one);


        //对象2
        String studenBoString = GsonUtil.toJson(studentA);
        StudentBO studentBO = GsonUtil.fromJson(studenBoString, StudentBO.class);
        System.out.println(studentBO);


        //数组
        List<Integer> numList = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        String numListJsonString = GsonUtil.toJson(numList);
        System.out.println(numListJsonString);

        //对象数组
        String studenBOListJsonString = GsonUtil.toJson(studentBOList);
        System.out.println(studenBOListJsonString);

        //对象数组实例化
        List<StudentBO> list = GsonUtil.fromJson(studenBOListJsonString, new TypeToken<List<StudentBO>>() {}.getType());
        System.out.println(list);

    }
}
